package org.locker.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.locker.domain.WechatMpUser;
import org.locker.mapper.WechatMpUserMapper;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private WechatMpUserMapper wechatMpUserMapper;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        // 获取微信用户基本信息
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                .userInfo(wxMessage.getFromUser(), null);
            if (userWxInfo != null) {
                // 保存信息
                String mpAppId = weixinService.getWxMpConfigStorage().getAppId();
                WechatMpUser wechatMpUser = wechatMpUserMapper.selectOne(new LambdaQueryWrapper<WechatMpUser>().eq(WechatMpUser::getAppId, mpAppId)
                        .eq(WechatMpUser::getOpenId, wxMessage.getFromUser()));
                if(wechatMpUser!=null){
                    wechatMpUser.setUnionId(userWxInfo.getUnionId());
                    wechatMpUser.setIsSubscribe(1l);
                    wechatMpUserMapper.updateById(wechatMpUser);
                }else{
                    wechatMpUser=new WechatMpUser();
                    wechatMpUser.setAppId(mpAppId);
                    wechatMpUser.setOpenId(userWxInfo.getOpenId());
                    wechatMpUser.setUnionId(userWxInfo.getUnionId());
                    wechatMpUser.setIsSubscribe(1l);
                    wechatMpUserMapper.insert(wechatMpUser);
                }
                // 扫码事件处理
                String eventKey = userWxInfo.getQrSceneStr();
                if(StrUtil.isNotBlank(eventKey)){
                    String[] keys = eventKey.split("@");
                    if(keys.length==2){
                        String appId=keys[0];
                        String deviceId=keys[1];
                        String content="<a data-miniprogram-appid=\""+appId+"\" data-miniprogram-path=\"pages/serve/bagCheck/index?deviceNo="+deviceId+"&bagtype=1\" data-miniprogram-nickname=\"\" data-miniprogram-type=\"text\" href=\" \">点我前往存包</a>" +
                                "\n\n" +
                                "<a data-miniprogram-appid=\""+appId+"\" data-miniprogram-path=\"pages/index/index\" data-miniprogram-nickname=\"\" data-miniprogram-type=\"text\" href=\" \">点我前往取包</a>";
                        WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content)
                                .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                                .build();
                        return m;
                    }
                }
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }


        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = this.handleSpecial(wxMessage);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }

        try {
//            return new TextBuilder().build("感谢关注", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
        throws Exception {
        //TODO
        return null;
    }

}
